package tempo.timing;

import org.json.JSONException;
import org.json.JSONObject;

public class Rider implements Comparable<Rider>
{
	private String startNumber;
	private String name;
	private long startTime = -1;
	private long finishTime = -1;

	public Rider()
	{

	}

	public Rider(String name, String number)
	{
		this.name = name;
		this.startNumber = number;
	}

	public void setStartNumber(String startNumber)
	{
		this.startNumber = startNumber;
	}

	public String getStartNumber()
	{
		return startNumber;
	}

	public void setRiderName(String name)
	{
		this.name = name;
	}

	public String getRiderName()
	{
		return name;
	}

	public void setStartTime(long startTime)
	{
		this.startTime = startTime;
	}

	public long getStartTime()
	{
		return startTime;
	}

	public void setFinishTime(long finishTime)
	{
		this.finishTime = finishTime;
	}

	public long getFinishTime()
	{
		return finishTime;
	}

	public long getResult()
	{
		if (startTime == -1 && finishTime == -1)
			return -1;
		if (finishTime == -1)
			return System.currentTimeMillis() - startTime;
		return finishTime - startTime;
	}

	public String GetStringResult()
	{
		long diff = 0;
		if (startTime == -1)
			return "00:00";
		if (finishTime == -1)
			diff = System.currentTimeMillis() - startTime;
		else
			diff = finishTime - startTime;
		long MINConst = 1000 * 60; 

		long min = diff / MINConst;
		long sec = (diff - min * MINConst) / 1000;
		if (sec < 10)
			return Long.toString(min) + ":0" + Long.toString(sec);
		else
			return Long.toString(min) + ":" + Long.toString(sec);

	}

	@Override
	public int compareTo(Rider another)
	{
		if (getResult() == another.getResult())
			return 0;
		if (getResult() == -1)
			return 1;
		if (getResult() > another.getResult())
			return 1;
		return -1;
	}

	public void LoadFrom(JSONObject json)
	{
		try
		{
			name = json.getString("name");
			startTime = json.getLong("startTime");
			finishTime = json.getLong("finishTime");
			startNumber = json.getString("startNumber");

		} catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public JSONObject Save()
	{
		JSONObject json = new JSONObject();
		try
		{
			json.put("name", name);
			json.put("startTime", startTime);
			json.put("finishTime", finishTime);
			json.put("startNumber", startNumber);
		} catch (JSONException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return json;
	}

	public void reset()
	{
		startTime = -1;
		finishTime = -1;
	}
}
